package com.base.cn.platform.os.controller.course.cou;

import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.md5.MD5;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.course.CourseContentUtil;
import com.base.cn.platform.os.common.utils.course.CourseType;
import com.base.cn.platform.os.common.utils.order.ShopType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.controller.cmmon.ApiBaseController;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogService;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.op.activity.OpActivityService;
import com.base.cn.platform.os.service.upload.LoggerGenService;
import com.google.gson.reflect.TypeToken;
import io.netty.util.internal.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 课程接口Controller
 *
 * @author s.li
 * @create 2018-09-05-20:25
 */
@RestController
@RequestMapping("/api/course")
public class ApiCourseController extends ApiBaseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private CommonConstants commonConstants;
    @Autowired
    private CourseCatalogService courseCatalogService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private LoggerGenService loggerGenService;
    @Value("${api.path}")
    private String apiPath;
    @Autowired
    private OpActivityService opActivityService;


    /**
     * 获取可以推广的课程列表
     * @param userId 用户ID
     * @return
     */
    @RequestMapping("/extension")
    public Map<String,Object> extension(@RequestParam("userId") BigDecimal userId,
                                        @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage){
        Map<String,Object> params = new HashMap<>();
        params.put("status",1);
        params.put("allow",2);
        params.put("type", 1);
        Map<String,Object> dataMap = courseService.findWebCoursePage(params,currentPage,10,true,false,false,true,false);
        if(ObjectUtils.isNotEmpty(dataMap)){
            List<Map<String,Object>> courseList = (List<Map<String,Object>>)dataMap.get("list");
            if(ObjectUtils.isNotEmpty(courseList)){
                courseList.forEach(course->{
                    String mobilePath = commonConstants.get(CommonConstants.MOBILE_PATH);
                    String shareUrl = mobilePath +"/mobile/course/info?courseId="+course.get("id")+"&shareKey="+ MD5.getMD5(userId.toString())+"_"+userId;
                    course.put("shareUrl",shareUrl);
                });
            }
        }
        return ResultUtil.SUCCESS(dataMap);
    }

    /**
     * 课程推荐列表接口
     * @param userId 用户ID
     * @return Map<String,Object>
     */
    @RequestMapping("/queryRecommendedCourseList")
    public Map<String,Object> queryRecommendedCourseList(@RequestParam(value = "userId",required = false,defaultValue = "0") BigDecimal userId){
        Map<String, Object> result = courseService.getAppH5RecommendIndex(userId);
        return ResultUtil.SUCCESS(result);
    }

    /**
     * 查询课程数据列表
     * @param courseTypeKey 课程类型 VIDEO视频，LIVE直播，COLUMNS文章，PACKAGE套餐
     * @param courseName 课程名
     * @param subjectIds 专业ID，多个以“,”隔开
     * @param teacherIds 老师ID，多个以“,”隔开
     * @param year 年份
     * @param orderType 排序条件,1更新时间倒序排序,2更新时间升序排序,3价格倒序排序,4价格升序排序
     * @param currentPage 页码
     * @return Map<String,Object>
     */
    @RequestMapping("/getAllCourseList")
    public Map<String,Object> getAllCourseList(@RequestParam(value = "courseTypeKey",required = false) String courseTypeKey,
                                               @RequestParam(value = "courseName",required = false) String courseName,
                                               @RequestParam(value = "subjectIds",required = false) String subjectIds,
                                               @RequestParam(value = "teacherIds",required = false) String teacherIds,
                                               @RequestParam(value = "year",required = false) String year,
                                               @RequestParam(value = "orderType",required = false) Integer orderType,
                                               @RequestParam(value = "currentPage",required = false,defaultValue = "1") Integer currentPage,
                                               @RequestParam(value = "isNotTypeKey",required = false,defaultValue = "true") boolean isNotTypeKey){
        Map<String,Object> params = new HashMap<>();
        params.put("status",1);
        params.put("type",1);
        params.put("courseTypeKey",courseTypeKey);
        params.put("courseName",courseName);
        params.put("subjectIds",subjectIds);
        params.put("teacherIds",teacherIds);
        params.put("year",year);
        params.put("orderType",orderType);
        if(isNotTypeKey){
            params.put("notCourseTypeKeys", "'" + CourseType.COURSE_TYPE_LIVE.getKey() + "','" + CourseType.COURSE_TYPE_SMALL.getKey() + "'");
        }
        Map<String,Object> dataMap = courseService.findWebCoursePage(params,currentPage,10,true,false,false,true,false);
        return ResultUtil.SUCCESS(dataMap);
    }

    /**
     * 加载直播课程列表
     * @param subjectIds  专业ID
     * @param courseName  课程名
     * @param orderType   排序条件,1更新时间倒序排序,2更新时间升序排序,3价格倒序排序,4价格升序排序
     * @param currentPage 页码
     * @return Map<String,Object>
     */
    @RequestMapping("/liveCourseList")
    public Map<String,Object> liveCourseList( @RequestParam(value = "subjectIds",required = false) String subjectIds,
                                              @RequestParam(value = "courseName",required = false) String courseName,
                                              @RequestParam(value = "orderType",required = false) Integer orderType,
                                              @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage) {
        Map<String,Object> params = new HashMap<>();
        params.put("status", 1);
        params.put("type", 1);
        params.put("subjectIds",subjectIds);
        params.put("orderType",orderType);
        params.put("courseName",courseName);
        params.put("courseTypeKey", CourseType.COURSE_TYPE_LIVE.getKey());
        Map<String, Object> dataMap = courseService.findWebCoursePage(params, currentPage, 10, true, false, false, true,true);
        return ResultUtil.SUCCESS(dataMap);
    }

    /**
     * 直播详情页
     * @return Map<String,Object>
     */
    @RequestMapping("/liveInfo")
    public Map<String,Object> newLiveInfo(HttpServletRequest request,
                                          @RequestParam(value = "userId",required = false,defaultValue = "0") BigDecimal userId,
                                          @RequestParam("courseId") BigDecimal courseId){
        Map<String, Object> course = courseService.findToBuyCourseById(courseId, userId,true, true, true, false, false, true,true);
        String path = apiPath+"/api/app/customerIndex";
        if (course.get("validType").equals(2)) {
            course.put("validTime",course.get("validTime").toString().split(" ")[0]);
            course.put("dontBuyTime",course.get("dontBuyTime").toString().split(" ")[0]);
        }
        TreeMap<String,String> config = sysConfigService.getSysConfigContext(ConfigName.SALE);
        String selaSwitch = config.get("selaSwitch");
        course.put("freshCatalog",newCatalog(course.get("id").toString()));
        Map<String,Object> resultMap = ResultUtil.SUCCESS(course);
        resultMap.put("sealSwitch",selaSwitch);
        TreeMap<String,String> serviceMap = sysConfigService.getSysConfigContext(ConfigName.SERVICE);
        resultMap.put("customerUrl",serviceMap);
        resultMap.put("consultationUrl",path);
        TreeMap<String, String> sysConfigContext = sysConfigService.getSysConfigContext(ConfigName.ONOFF);
        boolean gotMoneySwitch =false;
        if(StringUtils.isNotEmpty(sysConfigContext.get("iosWithdraw"))&&sysConfigContext.get("iosWithdraw").equals("ON")){
            gotMoneySwitch=true;
        }
        resultMap.put("iosWithdraw",gotMoneySwitch);
        resultMap.put("shareUrl",commonConstants.get(CommonConstants.MOBILE_PATH) +"/mobile/course/liveInfo?courseId="+courseId+"&shareKey="+MD5.getMD5(userId.toString())+"_"+userId);
        course.put("courseService",setCourseService(Integer.valueOf(course.get("service").toString())));
        resultMap.put("courseInfoActivity",getCourseInfoActivity(Double.valueOf(course.get("realPrice").toString())));
        loggerGenService.genGoodsPVUVLog(courseId, ShopType.ORDER_SHOP_COURSE);
        return resultMap;
    }

    /**
     * 加载直播目录
     * @param userId 用户ID，未登录传０
     * @param courseId 直播课程ID
     * @return 页面
     */
    @RequestMapping("/loadLiveCatalog")
    public Map<String,Object> loadLiveCatalog(@RequestParam(value = "userId",required = false,defaultValue = "0") BigDecimal userId,
                                              @RequestParam("courseId") BigDecimal courseId){
        List<Map<String, Object>> courseCatalogList = courseCatalogService.findCourseCatalogLayeredByCourseId(courseId,userId,courseId, true, false, false, false,true);
        return ResultUtil.SUCCESS(courseCatalogList);
    }

    /**
     * 课程详情接口
     * @param courseId 课程ID
     * @param userId 用户ID
     * @return Map<String,Object>
     */
    @RequestMapping("/getCourseInfoById")
    public Map<String,Object> getCourseInfoById(HttpServletRequest request,
                                                @RequestParam("courseId") BigDecimal courseId,
                                                @RequestParam(value = "userId",required = false,defaultValue = "0") BigDecimal userId){
        Course course = courseService.findToBuyCourseManyById(courseId,userId,true,true,true,false,false,true,true);
        TreeMap<String,String> config = sysConfigService.getSysConfigContext(ConfigName.SALE);
        String selaSwitch = config.get("selaSwitch");
        course.setFreshCatalog(newCatalog(course.getId().toString()));
        course.setCourseService(setCourseService(course.getService()));
        Map<String,Object> resultMap = ResultUtil.SUCCESS(course);
        if (course.getValidType()==2) {
            String validTime = DateUtils.format(course.getValidTime(), "yyyy-MM-dd");
            String dontBuyTime = DateUtils.format(course.getDontBuyTime(), "yyyy-MM-dd");
            TreeMap<String,Object> entity = gson.fromJson(gson.toJson(course), new TypeToken<TreeMap<String, Object>>() {
            }.getType());
            entity.put("validTime", validTime);
            entity.put("dontBuyTime", dontBuyTime);
            resultMap = ResultUtil.SUCCESS(entity);
        }
        resultMap.put("sealSwitch",selaSwitch);
        String path = apiPath +"/api/app/customerIndex";
        TreeMap<String,String> serviceMap = sysConfigService.getSysConfigContext(ConfigName.SERVICE);
        resultMap.put("customerUrl",serviceMap);
        resultMap.put("shareUrl", commonConstants.get(CommonConstants.MOBILE_PATH) +"/mobile/course/info?courseId="+courseId+"&shareKey="+MD5.getMD5(userId.toString())+"_"+userId);
        resultMap.put("consultationUrl",path);
        TreeMap<String, String> sysConfigContext = sysConfigService.getSysConfigContext(ConfigName.ONOFF);
        boolean gotMoneySwitch =false;
        if(StringUtils.isNotEmpty(sysConfigContext.get("iosWithdraw"))&&sysConfigContext.get("iosWithdraw").equals("ON")){
            gotMoneySwitch=true;
        }
        resultMap.put("iosWithdraw",gotMoneySwitch);
        resultMap.put("courseInfoActivity",getCourseInfoActivity(course.getRealPrice()));
        loggerGenService.genGoodsPVUVLog(courseId, ShopType.ORDER_SHOP_COURSE);
        return resultMap;
    }

    /**
     * 课程目录
     * @param userId 用户ID（未登录传0）
     * @param buyCourseId 购买的课程ID（购买的课程ID或套餐ID）
     * @param courseId 课程ID（如果是普通课程，则填写购买的课程ID，如果是套餐，则是套餐下的课程ID）
     * @return Map<String,Object>
     */
    @RequestMapping("/getCourseCatalogByCourseId")
    public Map<String,Object> getCourseCatalogByCourseId(@RequestParam(value = "userId",required = false,defaultValue = "0") BigDecimal userId,
                                                         @RequestParam("buyCourseId") BigDecimal buyCourseId,
                                                         @RequestParam("courseId") BigDecimal courseId){
        List<Map<String,Object>> courseCatalogList = courseCatalogService.findCourseCatalogLayeredByCourseId(buyCourseId,userId,courseId,true, false, false, false,true);
        return ResultUtil.SUCCESS(courseCatalogList);
    }

    private String setCourseService(Integer service){
        return   CourseContentUtil.setCourseService(service,sysConfigService," . ");

    }

    private List<Map<String,Object>> getCourseInfoActivity(Double price){
            Map<String,String> map = new HashMap<>();
            map.put("price",String.valueOf(price));
            List<Map<String,String>> params = new ArrayList<>();
            params.add(map);
            List<Map<String,Object>> activityList = opActivityService.findOrderAvailableActivityList(params,false);
            for(Map result:activityList){
                Iterator<Map.Entry<String, Object>> it = result.entrySet().iterator();
                while (it.hasNext()) {
                  Map.Entry<String, Object> entry = it.next();
                  if(!entry.getKey().equals("activityName")&&!entry.getKey().equals("id")){
                      it.remove();
                  }
              }
            }
        return  activityList;
    }

    private String newCatalog(String id){
        StringBuffer  newCatalog =  new StringBuffer("");
        Map<String, Object> newCatalogMap = courseCatalogService.getNewCourseCatalog(id);
        if(ObjectUtils.isNotEmpty(newCatalogMap)){
            if(ObjectUtils.isNotEmpty(newCatalogMap.get("parentCatalog"))){
              Map parentCatalog = (Map) newCatalogMap.get("parentCatalog");
                newCatalog.append(parentCatalog.get("catalogName")).append("-");
            }
            newCatalog.append(newCatalogMap.get("catalogName"));
        }
        return newCatalog.toString();
    }



    /***************************小班课***************************/

    /**
     * 小班课课程列表课程列表
     * @param subjectIds  专业ID
     * @param courseName  课程名
     * @param orderType   排序条件,1更新时间倒序排序,2更新时间升序排序,3价格倒序排序,4价格升序排序
     * @param currentPage 页码
     * @return Map<String,Object>
     */
    @RequestMapping("/liveSmallCourseList")
    public Map<String,Object> liveSmallCourseList( @RequestParam(value = "subjectIds",required = false) String subjectIds,
                                                   @RequestParam(value = "courseName",required = false) String courseName,
                                                   @RequestParam(value = "orderType",required = false) Integer orderType,
                                                   @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage) {
        Map<String,Object> params = new HashMap<>();
        params.put("status", 1);
        params.put("type", 1);
        params.put("subjectIds",subjectIds);
        params.put("orderType",orderType);
        params.put("courseName",courseName);
        params.put("courseTypeKey", CourseType.COURSE_TYPE_SMALL.getKey());
        Map<String, Object> dataMap = courseService.findWebCoursePage(params, currentPage, 10, true, false, false, true,true);
        return ResultUtil.SUCCESS(dataMap);
    }


    /**
     * 小班课详情
     * @return Map<String,Object>
     */
    @RequestMapping("/smallCourseInfo")
    public Map<String,Object> smallCourseInfo(HttpServletRequest request,
                                              @RequestParam(value = "userId",required = false,defaultValue = "0") BigDecimal userId,
                                              @RequestParam("courseId") BigDecimal courseId){
        Map<String, Object> course = courseService.findToBuyCourseById(courseId, userId,true, true, true, false, false, true,true);
        String path = apiPath+"/api/app/customerIndex";

        course.put("freshCatalog",newCatalog(course.get("id").toString()));
        Map<String,Object> resultMap = ResultUtil.SUCCESS(course);
        TreeMap<String,String> serviceMap = sysConfigService.getSysConfigContext(ConfigName.SERVICE);
        resultMap.put("customerUrl",serviceMap);
        resultMap.put("consultationUrl",path);
        String type="1";
        String type1 = serviceMap.get("type");
        if(StringUtils.isNotEmpty(type1)){
            type=type1;
        }
        resultMap.put("customerType",type);
        course.put("courseService",setCourseService(Integer.valueOf(course.get("service").toString())));
        resultMap.put("courseInfoActivity",getCourseInfoActivity(Double.valueOf(course.get("realPrice").toString())));
        loggerGenService.genGoodsPVUVLog(courseId, ShopType.ORDER_SHOP_COURSE);
        return resultMap;
    }
}



